package com.seu.vcampus.view.library;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.vo.Book;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 编辑图书对话框
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class EditBookDialog extends JDialog {
    private VCampusClient client;
    private Book book;
    private JTextField titleField;
    private JTextField authorField;
    private JTextField publisherField;
    private JTextField isbnField;
    private JTextField stockField;
    private JButton confirmButton;
    private JButton cancelButton;
    private boolean confirmed = false;
    
    public EditBookDialog(JDialog parent, VCampusClient client, Book book) {
        super(parent, "编辑图书", true);
        this.client = client;
        this.book = book;
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        setSize(400, 450);
        setLocationRelativeTo(parent);
        setResizable(false);
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        setLayout(new BorderLayout());
        
        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridLayout(5, 2, 10, 10));
        inputPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        Font labelFont = new Font("微软雅黑", Font.BOLD, 14);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);
        
        // 书名
        JLabel titleLabel = new JLabel("书名:");
        titleLabel.setFont(labelFont);
        titleField = new JTextField(book.getTitle());
        titleField.setFont(fieldFont);
        
        // 作者
        JLabel authorLabel = new JLabel("作者:");
        authorLabel.setFont(labelFont);
        authorField = new JTextField(book.getAuthor());
        authorField.setFont(fieldFont);
        
        // 出版社
        JLabel publisherLabel = new JLabel("出版社:");
        publisherLabel.setFont(labelFont);
        publisherField = new JTextField(book.getPublisher());
        publisherField.setFont(fieldFont);
        
        // ISBN
        JLabel isbnLabel = new JLabel("ISBN:");
        isbnLabel.setFont(labelFont);
        isbnField = new JTextField(book.getIsbn());
        isbnField.setFont(fieldFont);
        
        // 库存数量
        JLabel stockLabel = new JLabel("库存数量:");
        stockLabel.setFont(labelFont);
        stockField = new JTextField(String.valueOf(book.getStock()));
        stockField.setFont(fieldFont);
        
        // 添加组件到面板
        inputPanel.add(titleLabel);
        inputPanel.add(titleField);
        inputPanel.add(authorLabel);
        inputPanel.add(authorField);
        inputPanel.add(publisherLabel);
        inputPanel.add(publisherField);
        inputPanel.add(isbnLabel);
        inputPanel.add(isbnField);
        inputPanel.add(stockLabel);
        inputPanel.add(stockField);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
        
        confirmButton = new JButton("确认修改");
        confirmButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        confirmButton.setBackground(new Color(40, 167, 69));
        confirmButton.setForeground(Color.BLACK);
        confirmButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        
        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelButton.setBackground(new Color(108, 117, 125));
        cancelButton.setForeground(Color.BLACK);
        cancelButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        
        buttonPanel.add(confirmButton);
        buttonPanel.add(cancelButton);
        
        add(inputPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        // 布局已在initializeComponents中设置
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        confirmButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateBook();
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        
        // 回车键确认
        getRootPane().setDefaultButton(confirmButton);
    }
    
    /**
     * 更新图书
     */
    private void updateBook() {
        String title = titleField.getText().trim();
        String author = authorField.getText().trim();
        String publisher = publisherField.getText().trim();
        String isbn = isbnField.getText().trim();
        String stockStr = stockField.getText().trim();
        
        // 验证输入
        if (title.isEmpty() || author.isEmpty() || 
            publisher.isEmpty() || isbn.isEmpty() || stockStr.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有必填字段", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        int stock;
        try {
            stock = Integer.parseInt(stockStr);
            if (stock < 0) {
                JOptionPane.showMessageDialog(this, "库存数量不能为负数", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "库存数量必须是整数", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 更新图书对象
        book.setTitle(title);
        book.setAuthor(author);
        book.setPublisher(publisher);
        book.setIsbn(isbn);
        book.setStock(stock);
        
        try {
            Message request = new Message(Message.Type.UPDATE_BOOK_REQUEST);
            request.setPayload(book);
            Message response = client.sendMessage(request);
            
            if (response.getType() == Message.Type.UPDATE_BOOK_RESPONSE) {
                Boolean success = (Boolean) response.getPayload();
                if (success) {
                    confirmed = true;
                    JOptionPane.showMessageDialog(this, "图书更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "图书更新失败，可能是ISBN已存在", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "更新图书失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 是否已确认
     */
    public boolean isConfirmed() {
        return confirmed;
    }
}